package com.flx.Interceptor;


import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.JwtUtil;
import vo.Result;

/**
 * @ClassName JwtTokenInterceptor
 * 自定义拦截器
 * @Author 23207
 * @Date 2025/4/21 9:08
 * @Version 1.0
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
  @Override // 在请求处理之前进行调用（Controller方法调用之前）
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    System.out.println("preHandle...运行了");
    // 获取 JWT 令牌
    String token = request.getHeader("token");
    if (token == null || token.isEmpty()) {
      System.out.println("未获取到token");

      Result error = Result.error("未登录,请先登录!");
      // 将信息返回给客户端
      String notLogin = JSON.toJSONString(error);
      response.setContentType("application/json;charset=UTF-8");
      response.getWriter().write(notLogin);

      return false;
    }

    try {
      JwtUtil.parseToken(token);
    } catch (Exception e) {
      System.out.println("令牌解析失败~~");

      Result error = Result.error("身份认证失效,请重新登录!");
      String notLogin = JSON.toJSONString(error);
      response.setContentType("application/json;charset=UTF-8");
      response.getWriter().write(notLogin);

      return false;
    }
    System.out.println("令牌解析成功!");
    return true;
  }

  // @Override // 在请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
  // public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  //   System.out.println("postHandle...运行了");
  // }
  //
  // @Override // 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行（主要是用于进行资源清理工作）
  // public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  //   System.out.println("afterCompletion...运行了");
  // }
}
